import React from 'react';
import { Form, Input, DatePicker, Button, Table, message, Popconfirm, Typography } from 'antd';
import { history } from 'umi'
// import { Pagination, AdvancedSearch } from '@/components';
import { AdvancedSearch } from '@/components';
import moment from 'moment';
import useManualGradeRuleList from '@/pages/Task/hooks/useManualGradeRule';
import StarRuleModal from './StarRuleModal';
import { deleteManualGradeRule } from '../../services';

const { RangePicker } = DatePicker;

const StarRule = ({ form, location, visible, setVisible, editId, isView, setIsView, setEditId, companyId }) => {
    const { getFieldDecorator, getFieldsValue } = form;
    const { query } = location;
    const { isExpand, ...fetchQuery } = query;

    const [ruleLoading, ruleList, fetchRuleList] = useManualGradeRuleList(fetchQuery);
    const dataSource = ruleList.map(item => ({ ...item, ...item.json }));

    const handleEdit = id => {
        setVisible(true);
        setEditId(id);
        setIsView(false);
    };

    const handleDelete = async id => {
        const result = await deleteManualGradeRule(id);
        if (result.code === 10000) {
            message.success('删除成功');
            fetchRuleList();
        } else {
            message.error(result.msg);
        }
    };

    const columns = [
        // {
        //     title: '排序',
        //     dataIndex: 'sort'
        // },
        {
            title: '评分指标',
            dataIndex: 'scoreTarget'
        },
        {
            title: '评分指标说明',
            dataIndex: 'scoreStandard',
            render: text => (
                <Typography.Text title={text} style={{ width: 200 }} ellipsis>
                    {text}
                </Typography.Text>
            )
        },
        {
            title: '评分星级',
            render: () => '五星'
        },
        {
            title: '每星分值',
            dataIndex: 'score',
            render: text => (Number.isNaN(text) ? text : Number(text).toFixed(1))
        },
        {
            title: '创建时间',
            dataIndex: 'createTime',
            sorter: (a, b) => moment(a.createTime).valueOf() - moment(b.createTime).valueOf()
        },
        {
            title: '操作',
            dataIndex: 'id',
            render: (text, record) => (
                <>
                    <Button
                        type="link"
                        onClick={() => {
                            handleEdit(record.id);
                        }}
                    >
                        编辑
                    </Button>
                    <Popconfirm
                        title="确定删除该评分规则？"
                        onConfirm={() => {
                            handleDelete(record.id);
                        }}
                    >
                        <Button type="link">删除</Button>
                    </Popconfirm>
                </>
            )
        }
    ];

    const setQuery = param => {
        history.push({ query: { ...query, ...param } });
    };

    // 搜索和重置，即使参数一样也要重新拉取
    const forceSearch = queryParam => {
        if (JSON.stringify(query) === JSON.stringify(queryParam)) {
            fetchRuleList();
            return true;
        }
        return false;
    };

    const handleSubmit = () => {
        const param = getFieldsValue();
        const { dateRange = [], ...rest } = param;
        let extraParam = { startTime: undefined, endTime: undefined };
        if (dateRange.length) {
            extraParam = {
                startTime: moment(dateRange[0])
                    .startOf('day')
                    .format('YYYY-MM-DD HH:mm:ss'),
                endTime: moment(dateRange[1])
                    .endOf('day')
                    .format('YYYY-MM-DD HH:mm:ss')
            };
        }
        const queryParam = {
            ...rest,
            ...extraParam
        };

        if (!forceSearch(queryParam)) setQuery(queryParam);
    };

    const handelReset = () => {
        if (!forceSearch({})) history.push({ query: {} });
    };

    // const handleTableChange = async (pagination, filters, sorter) => {
    //     console.log(pagination, filters, sorter);
    // };

    // const handlePaginationChange = _pagination => {
    //     setQuery(_pagination);
    // };

    const handleRowClick = (row = {}) => ({
        onClick(e) {
            // 是否有更好得办法？
            if (e.target.tagName === 'BUTTON' || !e.currentTarget.contains(e.target)) return;
            setVisible(true);
            setEditId(row.id);
            setIsView(true);
        }
    });

    return (
        <>
            <AdvancedSearch form={form} onSubmit={handleSubmit} onReset={handelReset}>
                <Form.Item label="评分指标">
                    {getFieldDecorator('scoreTarget', {
                        initialValue: query.scoreTarget || undefined
                    })(<Input placeholder="请输入评分指标" allowClear />)}
                </Form.Item>
                <Form.Item label="指标说明">
                    {getFieldDecorator('scoreStandard', {
                        initialValue: query.scoreStandard || undefined
                    })(<Input placeholder="请输入指标说明" allowClear />)}
                </Form.Item>
                <Form.Item label="创建时间">
                    {getFieldDecorator('dateRange', {
                        initialValue:
                            query.startTime && query.startTime
                                ? [moment(query.startTime), moment(query.endTime)]
                                : undefined
                    })(
                        <RangePicker
                            ranges={{
                                本周: [moment().startOf('week'), moment().endOf('week')],
                                本月: [moment().startOf('month'), moment().endOf('month')],
                                本季度: [moment().startOf('quarter'), moment().endOf('quarter')]
                            }}
                        />
                    )}
                </Form.Item>
            </AdvancedSearch>
            <Table
                rowKey="id"
                bordered={false}
                columns={columns}
                loading={ruleLoading}
                dataSource={dataSource}
                // onChange={handleTableChange}
                pagination={false}
                onRow={handleRowClick}
                scroll={{ x: 'max-content' }}
            />
            {/* <Pagination
                total={ruleTotal}
                current={Number(query.current)}
                pageSize={Number(query.pageSize)}
                onChange={handlePaginationChange}
                loading={ruleLoading}
            /> */}
            <StarRuleModal
                visible={visible}
                setVisible={setVisible}
                editId={editId}
                setEditId={setEditId}
                companyId={companyId}
                fetchRuleList={fetchRuleList}
                isView={isView}
            />
        </>
    );
};

export default Form.create()(StarRule);
